<?php
namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use app\common\model\mysql\User as UserModel;

class User{
    public $userObj = null;
    public function __construct()
    {
        $this->userObj = new UserModel();
    }


    /**
     * @param $data  phone_number
     */
    public function login($data){
        #从redis中取出手机号
        $redisCode = cache(config("redis.code_pre").$data['phone_number']);
        #判断是否有值
        if(empty($redisCode) || $redisCode != $data['code']){
            throw new \think\Exception("不存在该验证码");
        }

        #验证表中 是否有 当前用户记录
        # 生成token
        $userInfo = $this->userObj->getUserByPhoneNumber($data['phone_number']);


        //不存在  则保存用户
        if(!$userInfo){

            #组装入库数据
            $userInsertData = [
                'username' => '小熊维尼',
                'phone_number' => $data['code'],
            ];

            try {
                $this->userObj->save($userInsertData);
                $userId = $this->userObj->id;
            }catch (\Exception $e){
                throw new \think\Exception("数据库内部异常");
            }

        }else{
            #存在  更新数据

            $userId = $userInfo->id;
            $username = $userInfo->username;
        }

        $token = Str::getLoginToken($data['phone_number']);
        #保存在redis中数据
        $redisData = [
            'id' => $userId,
            "username" =>$username
        ];
        #做缓存   设置过期时间
        $res = cache(config("redis.token_pre").$token, $redisData,Time::userLoginExpiresTime($data['type']));

        return $res?["token"=>$token, "username"=> $username]:false;

    }


}